<?php

namespace App\Imports;

use Illuminate\Support\Arr;
use Maatwebsite\Excel\Concerns\ToArray;

class Statistical implements ToArray
{
    /**
     * @var array
     */
    private $config;

    public function __construct(array $config = [])
    {
        $this->config = $config;
    }

    /**
     * @var string[] 需要验证不能为空的字段
     */
    private $validateKeys = [
        '1.1',
        '1.2',
        '2.1',
        '2.2',
        '4.1',
        '4.2',
        '4.3',
    ];

    /**
     * @var string[] 字段映射
     */
    private $keysMaps = [
        '1.1' => 'success_amount',
        '1.2' => 'success_num',
        '2.1' => 'not_amount',
        '2.2' => 'not_num',
        '4.1' => 'user_count',
        '4.2' => 'user_two_count',
        '4.3' => 'user_three_count',
    ];


    /**
     * @param array $array
     *
     * @return array
     * @throws \Exception
     */
    public function array(array $array)
    {
        // 验证数据的有效性
        if (count($array) < 7) {
            throw new \Exception('导入数据存在问题');
        }

        // 验证数据信息
        foreach ($this->validateKeys as $key) {
            $value = Arr::get($array, $key);
            if ($value === '' || $value === null || !is_numeric($value)) {
                $rows = explode('.', $key);
                throw new \Exception('导入数据第' . $rows[0] . '行第' . $rows[1] . '列 请填写数字');
            }
        }

        foreach ($this->keysMaps as $key => $attribute) {
            $this->config[$attribute] = intval(Arr::get($array, $key));
        }

        return $this->config;
    }

    public function toArray()
    {
        return $this->config;
    }
}
